const { Service } = require('dx-router-admin');
const { UniIdUsers } = require('dx-func-entity');
const createConfig = require('uni-config-center');

module.exports = class User extends Service {
	constructor(ctx) {
		super(ctx);
		this.entity = UniIdUsers;
		this.append = ['gender_text'];
		const uniIdConfig = createConfig({
			pluginId: 'uni-id', // 插件id
		});
		let passwordSecret = uniIdConfig.config('passwordSecret');
		if (ctx.utils.isArray(passwordSecret)) {
			this.passwordSecret = passwordSecret[0];
		} else {
			this.passwordSecret = passwordSecret;
		}
	}
	getGenderTextAttr(value) {
		switch (value) {
			//1 男性 2 女性
			case 1:
				return '男';
			case 2:
				return '女';
			default:
				return '未知';
		}
	}
	// 获取密码加密方法
	getPasswordExtMethod(password) {
		return this.$dx.utils.getPasswordExtMethod(this.passwordSecret.type, this.passwordSecret).encrypt(password);
	}
	/**
	 * 注册管理员账号
	 */
	async createManageAccount() {
		let { passwordHash, version } = this.getPasswordExtMethod('123456');
		let role = ['admin'];
		let ip = this.$dx.request.ip;
		let time = new Date().getTime();
		let dcloud_appid = [];
		if (this.$dx.request.appId) {
			dcloud_appid.push(this.$dx.request.appId);
		}
		//初始化，是没有用户的，自动创建超级管理员
		let user = {
			nickname: '超级管理员',
			username: 'admin',
			password: passwordHash,
			password_secret_version: version,
			role,
			register_date: time,
			register_ip: ip,
			last_login_ip: ip,
			last_login_date: time,
			dcloud_appid,
			status: 0,
			gender: 0,
			email: '',
			mobile: '',
			avatar: '',
			money: 0,
			score: 0,
		};
		let uid = await this.insert(user);
		user._id = uid;
		return await this.loginByUser(user);
	}
	// 注册手机号码用户
	async createByMobile(mobile) {
		let ip = this.$dx.request.ip;
		let time = Date.now();
		let dcloud_appid = [];
		if (this.$dx.request.appId) {
			dcloud_appid.push(this.$dx.request.appId);
		}
		//初始化，是没有用户的，自动创建超级管理员
		let user = {
			// 手机号码中间四位隐藏
			nickname: mobile.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2'),
			username: mobile,
			role: [],
			mobile,
			register_date: time,
			register_ip: ip,
			last_login_ip: ip,
			last_login_date: time,
			status: 0,
			dcloud_appid,
			gender: 0,
			email: '',
			avatar: '',
			money: 0,
			score: 0,
		};
		let uid = await this.insert(user);
		user._id = uid;
		return await this.loginByUser(user);
	}
	/**
	 * 校验密码
	 * @param {string} password
	 * @param {string} passwordHash
	 * @param {number} version
	 */
	checkPassword(password, passwordHash, version) {
		return this.$dx.utils.getPasswordExtMethod(this.passwordSecret.type, this.passwordSecret).verify(password, passwordHash, version);
	}
	/**
	 * 获取当前登陆用户信息
	 */
	async getCurrentUserInfo() {
		const { role, permission, uid } = this.$dx.auth;
		const user = await this.where('_id', uid).find();
		const { token, tokenExpired } = await this.$dx.uniID.refreshToken({
			token: this.$dx.request.uniIdToken,
		});
		return {
			token,
			tokenExpired,
			permission,
			role,
			nickname: user.nickname,
			username: user.username,
			gender: user.gender,
			user_id: user._id,
			mobile: user.mobile,
			email: user.email,
			avatar: user.avatar,
			money: user.money,
			score: user.score,
			vip:user.vip
		};
	}
	// 登陆
	async loginByUser(user) {
		// 获取授权的角色
		let roleList = await this.$dx.service.role.where('role_id', 'in', user.role).select();
		// 合并权限
		let permission = roleList.reduce(function (arr, current) {
			return [...arr, ...current.permission];
		}, []);
		// 去重
		permission = [...new Set(permission)];
		let { token, tokenExpired, errCode, errMsg } = await this.$dx.uniID.createToken({
			uid: user._id,
			role: user.role,
			permission,
		});
		//登录后的日志
		await this.$dx.service.logs.addLoginLog(user._id, user.username, 'login', errCode ? 0 : 1, user.mobile, user.email);
		if (errCode) {
			this.$dx.error(errMsg);
		}
		return {
			token,
			tokenExpired,
			permission,
			role: user.role,
			username: user.username,
			nickname: user.nickname,
			gender: user.gender,
			user_id: user._id,
			mobile: user.mobile,
			email: user.email,
			avatar: user.avatar,
			money: user.money,
			score: user.score,
			vip:user.vip
		};
	}
	/**
	 * 前三次登录失败，锁定账户
	 * @param {stirng} uid
	 * @param {string} username
	 */
	async lockUser(uid, username) {
		const deviceId = this.$dx.request.deviceId;
		const now = Date.now();
		// 同一用户，用一设备，查询是否在 {2小时} 内 {前3条} 有 {登录失败} 数据，锁定用户
		const recordSize = 3;
		const recordDate = 120 * 60 * 1000;
		let total = await this.$dx.service.logs
			.where('device_uuid', deviceId)
			.where('username', username)
			.where('create_date', '>', now - recordDate)
			.where('type', 'login')
			.where('state', 0)
			.count();
		if (total >= recordSize) {
			await this.save({
				_id: uid,
				status: 1,
			});
		}
	}
};
